﻿# -*- coding: utf-8 -*-

# 插件加载方法： 
# 先运行 qqbot ，启动成功后，在另一个命令行窗口输入： qq plug qqbot.plugins.sample
import time
import os
from PIL import Image
from pytesseract import *
import requests
from io import BytesIO
ghhh={'Michael': 95, 'Bob': 75, 'Tracy': 85}
gmmm={'Michael': 95, 'Bob': 75, 'Tracy': 85}

def jwxtcjcx(zh,mm):#教务系统查成绩

    def cjzh(s):
        try:
            return float(s)
        except:
            if ('优秀' in s):
                return 100.0
            if ('良好' in s):
                return 85.0
            if ('中等' in s):
                return 75.0
            if ('及格' in s):
                return 65.0
            return 0.0

    def jsjd(jd):
        if (jd >= 90):
            return 5.0
        if (jd >= 85):
            return 4.5
        if (jd >= 80):
            return 4.0
        if (jd >= 75):
            return 3.5
        if (jd >= 70):
            return 3.0
        if (jd >= 65):
            return 2.5
        if (jd >= 60):
            return 2.0
        return 0.0

    def yzm(s):  # s是图片本地路径
        im = Image.open(s)
        imgry = im.convert('L')  # 把图片变成灰色
        threshold = 140

        table = []

        for i in range(256):  # 二值化变成黑白

            if i < threshold:
                table.append(0)
            else:
                table.append(1)
        out = imgry.point(table, '1')
        asd = pytesseract.image_to_string(out, lang='fyx')  # 然后就是机器识别咯，lang包来自小贩子的喂图调教成果（机器学习）~~~
        return asd

    #zh = input('输入账号:\n')
    #mm = input('输入密码:\n')
    img_src = 'http://202.119.113.135/validateCodeAction.do?random=0.5'  # 获取验证码的链接
    url = 'http://202.119.113.135/gradeLnAllAction.do?type=ln&oper=qbinfo&lnxndm'
    url1 = 'http://202.119.113.135/loginAction.do'  # 登录链接
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/52.0'}  # 请求头
    '''
    fw函数是用来验证密码是否正确的函数
    mm参数是密码
    xc参数是线程编号~~
    '''

    def dl(zh, mm):  # 登录
        valcode = requests.get(img_src)  # 从验证码链接获取图片
        cookies = valcode.cookies.get_dict()  # 保存cookies
        image = Image.open(BytesIO(valcode.content))  # 图片获取
        # path1 = os.path.abspath('.')
        lj = 'yzm.bmp'  # 图片保存路径
        try:
            image.save(lj)  # 保存图片
        except:
            return dl(xc, mm)
        yzm_str = yzm(lj)
        if (len(yzm_str) != 4):  # 验证码不是4位说明识别出错
            return dl(zh, mm)
        mms = str(mm)
        while (len(mms) < 6):  # 密码补0
            mms = '0' + mms
        data = {  # 需要post的数据
            "zjh": str(zh),
            "mm": mms,
            "v_yzm": yzm_str,
        }
        response = requests.post(url1, data=data, headers=headers, cookies=cookies)  # 获取网页
        htxt = response.text  # 网页源代码
        if ('您的密码不正确，请您重新输入' in htxt):

            return ('密码错误')
        elif ('你输入的验证码错误' in htxt):
            return dl(zh, mm)
        else:

            response = requests.get(url, headers=headers, cookies=cookies)  # 获取网页
            return response.text

    s = dl(zh, mm)
    if (s == '0'):
        return ('导出失败')
    else:
        pass

    kch = ['课程号']  # 课程号
    kxh = ['课序号']  # 课序号
    kcm = ['课程名']  # 课程名
    ywkcm = ['英文课程名']  # 英文课程名
    xf = ['学分']  # 学分
    kcsx = ['课程属性']  # 课程属性
    cj = ['成绩']  # 成绩
    jd = ['绩点']  # 绩点
    bg = [0, kch, kxh, kcm, ywkcm, xf, kcsx, 0, cj, jd]  # 表格
    k = 0
    sx = 0
    xieru = False
    s = s.split('\n')
    gks = 0
    for line in s:
        if xieru:
            if sx == 7:
                sx = 8
                continue
            zj = line.strip()
            if (sx == 8):
                zj = zj.split('&')[0]
                zj = zj.split('>')[1]
                zj = cjzh(zj)
                zj = float(zj)
                if zj < 60:
                    gks += 1
                jd.append(jsjd(zj))

            x = bg[sx]
            x.append(zj)

            xieru = False
            continue
        if 'onMouseOut' in line:
            k += 1
            sx = 0
        if 'td align="' in line and 'center' in line:
            sx += 1
            xieru = True
    '''
    print(kch)
    print(kxh)
    print(kcm)
    print(ywkcm)
    print(xf)
    print(kcsx)
    print(cj)
    print(jd)
    '''
    i = 1

    zjd = 0.0
    zxf = 0.0
    zcj = 0.0
    while i < len(kch):
        #print('\n\n第' + str(i) + '门:')
        k = 1
        s = ''
        while k < len(bg):
            if k == 7:
                k = 8
            if k == 5:
                zxf += float(bg[k][i])
            if k == 8:
                zcj += float(bg[k][i]) * float(bg[5][i])
            if k == 9:
                zjd += float(bg[k][i]) * float(bg[5][i])
            s = s + bg[k][0] + ':' + str(bg[k][i]) + '\n'
            k += 1
        print(s)
        i += 1
    s='一共有' + str(len(kch) - 1) + '门课程，您一共挂了' + str(gks) + '科~~\n'+'您的加权绩点为:\n' + str(zjd / zxf)+'\n您的加权成绩为;\n' + str(zcj / zxf)
    return s


def mkdir(path):
    folder = os.path.exists(path)
    if not folder:  # 判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(path)  # makedirs 创建文件时如果路径不存在会创建这个路径
def cs(s):
    file = open('cs.txt', 'a')
    try :
        file.write(s)
    except :
        return False
    return True
def jc(s):#看看是不是有乱码
    print('~~~')
    i=0
    cd=len(s)-1
    zh=''
    while i<cd:
        z = s[i]
        if(cs(z)):
            zh=zh+z


        i = i + 1


    return zh

def onQQMessage(bot, contact, member, content):
    global ghhh
    global gmmm
    sj = time.strftime("%Y%m%d")
    lj='E:/qqjl/'+sj
    mkdir(lj)
    lj=lj+'/'+str(contact)+'.txt'
    print(lj)
    file=open(lj,'a')
    if member!=None :
        s=str(member)+':  '+str(content)+'\r\n'
    else:
        s = str(contact) + ':' + str(content) + '\r\n'
    s= time.strftime("%H:%M:%S  ")+s+ '\r\n'+ '\r\n'+ '\r\n'
    try :
        file.write(s)
    except :
        s=jc(s)
        file.write(s)
    file.close()
    if ( '2018计信院新生群' in contact.name or '河海ACM交流群' in contact.name or '兼职社福利与服务平台' in contact.name or '南京莆仙同学会' in contact.name or '河海大学2017级新生' in contact.name):
        print('1111\n\n')
    elif ( '2018河海大学暖新舍' in contact.name or '河海大学福建老乡群' in contact.name or '16 胡捷耀' in contact.name or 'QQ小冰' in contact.name or '17河海莆仙' in contact.name):
        print('1111\n\n')
    else :
        return

    mmm=time.strftime("%M")
    mmm=int(mmm)
    hhh=time.strftime("%H")
    hhh=int(hhh)
    mz=contact.name
    if(mz in ghhh)==False:

        ghhh[mz]=hhh
        gmmm[mz]=mmm-15
    elif(hhh==ghhh[mz] and mmm<gmmm[mz]+10):
        return
    elif(hhh!=ghhh[mz] and mmm+60<gmmm[mz]+10):
        return

    if('福建'in s or '莆田' in s or '莆仙' in s):
        ghhh[mz]=hhh
        gmmm[mz]=mmm
        bot.SendTo(contact,'河海莆田老乡群了解一下，群号：5418210 ~~ （机器人自动发送，不要回复咯，莆田人自己加一下咯）')


    if '成绩查询'in content:
        zh=''
        mm=''
        pdzh = False
        pdmm = False
        for zf in content:
            if(zf=='1'):
                pdzh=True
            if pdzh and zf==' ':
                pdmm=True
            if(pdzh and pdmm==False):
                zh=zh+zf
            if pdmm :
                mm=mm+zf
        mm = mm.replace('密码', '')
        zh = zh.strip()
        mm = mm.strip()
        if mm[0]==':'or mm[0]=='：':
            mm=mm[1:]

        print(zh,mm)
        cj=jwxtcjcx(zh,mm)
        bot.SendTo(contact, cj)


